import { provide, inject, ref, unref } from 'vue'
import { message as Message } from 'ant-design-vue'
import { debounce } from 'lodash-es'
import { nanoid } from 'nanoid'
import { roleList } from '@/api/role.js'
/**
 * Symbol
 */
export const columnsSymbol = Symbol('columns')
export const dataSourceSymbol = Symbol('dataSource')
export const querySymbol = Symbol('query')
export const lineheightSymbol = Symbol('lineheight')
export const loadingSymbol = Symbol('loading')

/**
 * 注册
 */
export function useProvideContextRegistry() {
  let columns = ref([])
  let dataSource = ref([])
  let query = ref({})
  let lineheight = ref()
  let loading = ref(false)

  provide(columnsSymbol, columns)
  provide(dataSourceSymbol, dataSource)
  provide(querySymbol, query)
  provide(lineheightSymbol, lineheight)
  provide(loadingSymbol, loading)
}

/**
 * 获取值
 */
export function useColumns() {
  return inject(columnsSymbol)
}
export function useDataSource() {
  return inject(dataSourceSymbol)
}
export function useQuery() {
  return inject(querySymbol)
}
export function useLineheight() {
  return inject(lineheightSymbol)
}
export function useLoading() {
  return inject(loadingSymbol)
}

/**
 * 管理工具
 */
export function useDataSourceManager() {
  let dataSource = useDataSource()
  let query = useQuery()
  let loading = useLoading()

  let update = debounce(async () => {
    loading.value = true
    let { current, pageSize } = query.value

    try {
      // dataSource.value = ds()
      let result = await roleList({
        pageIndex: current,
        pageSize,
        keyWord: query.value.keyWord,
      })
      dataSource.value = result.data.records
      query.value.current = result?.data?.current || current
      query.value.pageSize = result?.data?.size || pageSize
      query.value.total = result?.data?.total || 0
      loading.value = false
    } catch (e) {
      Message.error('列表加载失败')
      loading.value = false
    }
  }, 300)

  return { update }
}
export function useQueryManager() {
  let query = useQuery()
  return {
    set(newQuery) {
      query.value = unref(newQuery)
    },
    assign(newQuery) {
      query.value = Object.assign({}, query.value, newQuery)
    },
  }
}
/**
 * 数据
 */
let ds = () =>
  Array(100)
    .fill(1)
    .map((i, index) => ({
      id: index + '',
      key: index,
      roleName: '工程师' + index,
      roleDesc:
        '负责设计、分析和优化数据管理平台数据管理平台数据管理平台数据管理平台数据管理平台数据管理平台数据管理平台',
      dataScope: 'C919',
      allowedActions: '查看、上传',
    }))
